﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace SysMonitor
{
    partial class Service1 : ServiceBase
    {
        #region Attributes

        protected Thread MonitorThread;
        protected System.Timers.Timer myTimer = new System.Timers.Timer();
        protected string FileDir = ConfigurationManager.AppSettings["LogFile"].ToString();
        protected string ErrLog = ConfigurationManager.AppSettings["LogFile"].ToString() + @"\err.log";
        protected string InterVal = ConfigurationManager.AppSettings["Interval"].ToString();
        protected List<string> Columns = new List<string>();

        private Object thisLock = new Object();

        #endregion

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                // TODO: 在此处添加代码以启动服务。
                bool issel = false;

                Columns.Add("日期");
                Columns.Add("时间");
                string Disk = ConfigurationManager.AppSettings["Disk"];
                if (Disk == "1")
                {
                    GlobalAtrrib.myInfo.Disk = true;
                    DriveInfo[] mydrivers = DriveInfo.GetDrives();
                    foreach (DriveInfo mydriver in mydrivers)
                    {
                        if (mydriver.DriveType == DriveType.Fixed) Columns.Add(mydriver.RootDirectory.Name + "(GB)");
                    }
                    issel = true;
                }
                else GlobalAtrrib.myInfo.Disk = false;
                string Memory = ConfigurationManager.AppSettings["Memory"];
                if (Memory == "1")
                {
                    GlobalAtrrib.myInfo.Memory = true;
                    Columns.Add("内存(MB)");
                    issel = true;
                }
                else GlobalAtrrib.myInfo.Memory = false;
                string CPU = ConfigurationManager.AppSettings["CPU"];
                if (CPU == "1")
                {
                    GlobalAtrrib.myInfo.CPU = true;
                    Columns.Add("CPU");
                    issel = true;
                }
                else GlobalAtrrib.myInfo.CPU = false;

                if (!issel)
                {
                    OutLog(ErrLog, "未选择监控对象");
                    return;
                }

                MonitorThread = new Thread(new ThreadStart(myMonitor));
                MonitorThread.Start();
                this.myTimer.Interval = int.Parse(InterVal) * 60 * 1000;
                this.myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
                this.myTimer.Start();
            }
            catch (Exception ex)
            {
                OutLog(ErrLog, ex.Message);
            }
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }

        #region Timer

        private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (MonitorThread == null || !MonitorThread.IsAlive)
            {
                MonitorThread = new Thread(new ThreadStart(myMonitor));
                MonitorThread.Start();
            }
        }

        #endregion

        #region Thread

        private void myMonitor()
        {
            List<string> item = Monitor.Start();
            item.Insert(0, DateTime.Now.ToString("yyyy-MM-dd"));
            AddLog(item);
        }

        #endregion

        #region Method

        private void AddLog(List<string> item)
        {
            string filetype = ConfigurationManager.AppSettings["RecordType"];
            string RecordFile = null;
            switch (filetype)
            {
                case "0":
                    try
                    {
                        RecordFile = FileDir + (FileDir.EndsWith(@"\") ? "" : @"\") + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                        if (!Export.Export2Txt(Columns, item, RecordFile))
                        {
                            OutLog(ErrLog, "文件" + RecordFile + "写入失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        OutLog(ErrLog, "文件" + RecordFile + "写入失败,错误信息：" + ex.Message);
                    }
                    break;
                case "1":
                    try
                    {
                        RecordFile = FileDir + (FileDir.EndsWith(@"\") ? "" : @"\") + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
                        if (!Export.Export2CSV(Columns, item, RecordFile))
                        {
                            OutLog(ErrLog, "文件" + RecordFile + "写入失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        OutLog(ErrLog, "文件" + RecordFile + "写入失败,错误信息：" + ex.Message);
                    }
                    break;
                case "2":
                    try
                    {
                        RecordFile = FileDir + (FileDir.EndsWith(@"\") ? "" : @"\") + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
                        if (!Export.Export2Excel(Columns, item, RecordFile))
                        {
                            OutLog(ErrLog, "文件" + RecordFile + "写入失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        OutLog(ErrLog, "文件" + RecordFile + "写入失败,错误信息：" + ex.Message);
                    }
                    break;
                default:
                    try
                    {
                        RecordFile = FileDir + @"\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                        if (!Export.Export2Txt(Columns, item, RecordFile))
                        {
                            OutLog(ErrLog, "文件" + RecordFile + "写入失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        OutLog(ErrLog, "文件" + RecordFile + "写入失败,错误信息：" + ex.Message);
                    }
                    break;
            }
        }

        public void OutLog(string txtName, string txt)
        {
            lock (thisLock)
            {
                FileStream fs = null;
                StreamWriter text = null;
                try
                {
                    fs = new FileStream(txtName, FileMode.Append, FileAccess.Write, FileShare.Read);
                    text = new StreamWriter(fs);
                    text.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + txt);
                    text.Flush();
                }
                catch
                {
                }
                finally
                {
                    fs.Dispose();
                }
            }
        }

        #endregion
    }
}
